<template>
  <view class="role-detail-page">
    <view class="header">
      <text class="title">角色详情</text>
      <button v-if="role && !role.isSystem" class="edit-btn" @click="editRole">
        编辑角色
      </button>
    </view>
    
    <view v-if="role" class="role-content">
      <!-- 基本信息 -->
      <view class="info-section">
        <view class="section-title">基本信息</view>
        <view class="info-grid">
          <view class="info-item">
            <text class="label">角色名称:</text>
            <text class="value">{{ role.name }}</text>
          </view>
          <view class="info-item">
            <text class="label">显示名称:</text>
            <text class="value">{{ role.displayName }}</text>
          </view>
          <view class="info-item">
            <text class="label">角色类型:</text>
            <text class="value" :class="role.isSystem ? 'system' : 'custom'">
              {{ role.isSystem ? '系统角色' : '自定义角色' }}
            </text>
          </view>
          <view class="info-item">
            <text class="label">状态:</text>
            <text class="value" :class="role.status === 1 ? 'active' : 'inactive'">
              {{ role.status === 1 ? '启用' : '禁用' }}
            </text>
          </view>
          <view class="info-item full-width">
            <text class="label">描述:</text>
            <text class="value">{{ role.description || '暂无描述' }}</text>
          </view>
        </view>
      </view>
      
      <!-- 权限列表 -->
      <view class="permissions-section">
        <view class="section-title">
          权限列表 ({{ permissions.length }})
        </view>
        <view class="permissions-grid">
          <view v-for="(perms, module) in groupedPermissions" :key="module" class="module-section">
            <view class="module-title">{{ module }}</view>
            <view class="permissions-list">
              <view v-for="permission in perms" :key="permission._id" class="permission-item">
                <view class="permission-info">
                  <text class="permission-name">{{ permission.displayName }}</text>
                  <text class="permission-desc">{{ permission.description }}</text>
                  <text class="permission-code">{{ permission.name }}</text>
                </view>
                <view class="permission-badge">
                  <text class="action-badge" :class="permission.action">
                    {{ getActionText(permission.action) }}
                  </text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 用户列表 -->
      <view class="users-section">
        <view class="section-header">
          <text class="section-title">使用该角色的用户 ({{ userCount }})</text>
          <button v-if="userCount > users.length" class="view-all-btn" @click="viewAllUsers">
            查看全部
          </button>
        </view>
        <view v-if="users.length > 0" class="users-list">
          <view v-for="user in users" :key="user._id" class="user-item">
            <view class="user-info">
              <text class="user-name">{{ user.username || user.phone }}</text>
              <text class="user-contact">{{ user.phone || user.email }}</text>
            </view>
            <view class="user-status">
              <text class="status-badge" :class="user.status === 1 ? 'active' : 'inactive'">
                {{ user.status === 1 ? '正常' : '禁用' }}
              </text>
            </view>
          </view>
        </view>
        <view v-else class="empty-users">
          <text>暂无用户使用该角色</text>
        </view>
      </view>
      
      <!-- 操作按钮 -->
      <view class="actions">
        <button v-if="!role.isSystem" class="danger-btn" @click="deleteRole">
          删除角色
        </button>
        <button class="assign-btn" @click="showAssignDialog">
          分配给用户
        </button>
      </view>
    </view>
    
    <view v-if="loading" class="loading">
      <text>加载中...</text>
    </view>
    
    <view v-if="!loading && !role" class="empty">
      <text>角色不存在</text>
    </view>
    
    <!-- 分配用户弹窗 -->
    <view v-if="showAssignUserDialog" class="dialog-overlay" @click="closeAssignDialog">
      <view class="dialog" @click.stop>
        <view class="dialog-header">
          <text class="dialog-title">分配角色给用户</text>
          <button class="close-btn" @click="closeAssignDialog">×</button>
        </view>
        <view class="dialog-content">
          <view class="search-section">
            <input 
              v-model="userSearch" 
              class="search-input" 
              placeholder="搜索用户..."
              @input="searchUsers"
            />
          </view>
          <view class="users-selector">
            <view v-for="user in searchResults" :key="user._id" class="user-option">
              <view class="user-info">
                <text class="user-name">{{ user.username || user.phone }}</text>
                <text class="user-contact">{{ user.phone || user.email }}</text>
                <text class="current-role">当前角色: {{ user.role }}</text>
              </view>
              <button class="assign-user-btn" @click="assignRoleToUser(user)">
                分配
              </button>
            </view>
          </view>
        </view>
        <view class="dialog-actions">
          <button class="cancel-btn" @click="closeAssignDialog">取消</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      role: null,
      permissions: [],
      groupedPermissions: {},
      users: [],
      userCount: 0,
      loading: false,
      roleId: null,
      
      // 分配用户相关
      showAssignUserDialog: false,
      userSearch: '',
      searchResults: []
    }
  },
  
  onLoad(options) {
    if (options.id) {
      this.roleId = options.id
      this.loadRoleDetail()
    }
  },
  
  methods: {
    async loadRoleDetail() {
      this.loading = true
      try {
        const res = await this.$api.get(`/permissions/roles/${this.roleId}`)
        const data = res.data.data
        
        this.role = data.role
        this.permissions = data.permissions
        this.users = data.users
        this.userCount = data.userCount
        
        // 按模块分组权限
        this.groupedPermissions = this.permissions.reduce((acc, permission) => {
          if (!acc[permission.module]) {
            acc[permission.module] = []
          }
          acc[permission.module].push(permission)
          return acc
        }, {})
      } catch (error) {
        uni.showToast({
          title: error.message || '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    getActionText(action) {
      const map = {
        create: '创建',
        read: '查看',
        update: '编辑',
        delete: '删除',
        manage: '管理'
      }
      return map[action] || action
    },
    
    editRole() {
      uni.navigateTo({
        url: `/pages/admin/permissions?tab=roles&edit=${this.roleId}`
      })
    },
    
    async deleteRole() {
      const res = await uni.showModal({
        title: '确认删除',
        content: `确定要删除角色"${this.role.displayName}"吗？删除后使用该角色的用户将失去相应权限。`
      })
      
      if (!res.confirm) return
      
      try {
        await this.$api.delete(`/permissions/roles/${this.roleId}`)
        uni.showToast({
          title: '角色删除成功'
        })
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      } catch (error) {
        uni.showToast({
          title: error.message || '删除失败',
          icon: 'none'
        })
      }
    },
    
    viewAllUsers() {
      uni.navigateTo({
        url: `/pages/admin/users?role=${this.role.name}`
      })
    },
    
    showAssignDialog() {
      this.showAssignUserDialog = true
      this.searchUsers()
    },
    
    closeAssignDialog() {
      this.showAssignUserDialog = false
      this.userSearch = ''
      this.searchResults = []
    },
    
    async searchUsers() {
      try {
        const res = await this.$api.get('/admin/users', {
          params: {
            search: this.userSearch,
            limit: 20
          }
        })
        this.searchResults = res.data.data.users
      } catch (error) {
        console.error('搜索用户失败:', error)
      }
    },
    
    async assignRoleToUser(user) {
      const res = await uni.showModal({
        title: '确认分配',
        content: `确定要将角色"${this.role.displayName}"分配给用户"${user.username || user.phone}"吗？`
      })
      
      if (!res.confirm) return
      
      try {
        await this.$api.post(`/permissions/users/${user._id}/assign-role`, {
          roleName: this.role.name
        })
        
        uni.showToast({
          title: '角色分配成功'
        })
        
        this.closeAssignDialog()
        this.loadRoleDetail()
      } catch (error) {
        uni.showToast({
          title: error.message || '分配失败',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style scoped>
.role-detail-page {
  padding: 20rpx;
  background: #f5f5f5;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
  padding: 20rpx;
  background: white;
  border-radius: 12rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
}

.edit-btn {
  background: #007aff;
  color: white;
  border: none;
  border-radius: 8rpx;
  padding: 16rpx 32rpx;
  font-size: 28rpx;
}

.role-content {
  display: flex;
  flex-direction: column;
  gap: 30rpx;
}

.info-section, .permissions-section, .users-section {
  background: white;
  border-radius: 12rpx;
  padding: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.view-all-btn {
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 6rpx;
  padding: 12rpx 24rpx;
  font-size: 24rpx;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.info-item.full-width {
  grid-column: 1 / -1;
}

.label {
  font-size: 24rpx;
  color: #999;
}

.value {
  font-size: 28rpx;
  color: #333;
}

.value.system {
  color: #722ed1;
}

.value.custom {
  color: #1890ff;
}

.value.active {
  color: #52c41a;
}

.value.inactive {
  color: #ff4d4f;
}

.permissions-grid {
  display: flex;
  flex-direction: column;
  gap: 30rpx;
}

.module-section {
  border: 1rpx solid #f0f0f0;
  border-radius: 8rpx;
  overflow: hidden;
}

.module-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  padding: 20rpx;
  background: #f8f9fa;
  border-bottom: 1rpx solid #f0f0f0;
}

.permissions-list {
  display: flex;
  flex-direction: column;
}

.permission-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.permission-item:last-child {
  border-bottom: none;
}

.permission-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4rpx;
}

.permission-name {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.permission-desc {
  font-size: 24rpx;
  color: #666;
}

.permission-code {
  font-size: 20rpx;
  color: #999;
  font-family: monospace;
}

.permission-badge {
  display: flex;
  align-items: center;
}

.action-badge {
  font-size: 20rpx;
  padding: 4rpx 12rpx;
  border-radius: 4rpx;
  color: white;
}

.action-badge.create {
  background: #52c41a;
}

.action-badge.read {
  background: #1890ff;
}

.action-badge.update {
  background: #fa8c16;
}

.action-badge.delete {
  background: #ff4d4f;
}

.action-badge.manage {
  background: #722ed1;
}

.users-list {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.user-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background: #f8f9fa;
  border-radius: 8rpx;
}

.user-info {
  display: flex;
  flex-direction: column;
  gap: 4rpx;
}

.user-name {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.user-contact {
  font-size: 24rpx;
  color: #666;
}

.user-status {
  display: flex;
  align-items: center;
}

.status-badge {
  font-size: 20rpx;
  padding: 4rpx 12rpx;
  border-radius: 4rpx;
}

.status-badge.active {
  background: #f6ffed;
  color: #52c41a;
}

.status-badge.inactive {
  background: #fff2f0;
  color: #ff4d4f;
}

.empty-users {
  text-align: center;
  padding: 60rpx;
  color: #999;
}

.actions {
  display: flex;
  gap: 20rpx;
  margin-top: 30rpx;
}

.danger-btn, .assign-btn {
  flex: 1;
  padding: 24rpx;
  border-radius: 8rpx;
  font-size: 32rpx;
  border: none;
}

.danger-btn {
  background: #ff4d4f;
  color: white;
}

.assign-btn {
  background: #52c41a;
  color: white;
}

.loading, .empty {
  text-align: center;
  padding: 60rpx;
  color: #999;
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog {
  background: white;
  border-radius: 12rpx;
  width: 90%;
  max-width: 600rpx;
  max-height: 80vh;
  overflow: hidden;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.dialog-title {
  font-size: 32rpx;
  font-weight: bold;
}

.close-btn {
  background: none;
  border: none;
  font-size: 48rpx;
  color: #999;
  padding: 0;
  width: 60rpx;
  height: 60rpx;
}

.dialog-content {
  padding: 30rpx;
  max-height: 60vh;
  overflow-y: auto;
}

.search-section {
  margin-bottom: 20rpx;
}

.search-input {
  width: 100%;
  padding: 20rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.users-selector {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
  max-height: 400rpx;
  overflow-y: auto;
}

.user-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  border: 1rpx solid #f0f0f0;
  border-radius: 8rpx;
}

.current-role {
  font-size: 20rpx;
  color: #999;
}

.assign-user-btn {
  background: #007aff;
  color: white;
  border: none;
  border-radius: 6rpx;
  padding: 12rpx 24rpx;
  font-size: 24rpx;
}

.dialog-actions {
  display: flex;
  gap: 20rpx;
  padding: 30rpx;
  border-top: 1rpx solid #f0f0f0;
}

.cancel-btn {
  flex: 1;
  padding: 24rpx;
  border-radius: 8rpx;
  font-size: 32rpx;
  border: none;
  background: #f5f5f5;
  color: #666;
}
</style>